package org.example.road.learn01;

import lombok.extern.slf4j.Slf4j;

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class BufTest {
    public static void main(String[] args) throws Exception{
        ReferenceQueue<Date> queue = new ReferenceQueue<>();
        // 垃圾回收之后，可以在queue内部找到name的对象
        // 这里定义了一个强引用
        Date now = new Date();
        // 一个弱引用
        WeakReference<Date> dRef1 = new WeakReference<>(new Date(), queue);
        // 一个强引用，一个弱引用
        WeakReference<Date> dRef2 = new WeakReference<>(now, queue);
        AtomicInteger counter = new AtomicInteger(1);

        // 把堆内存填满
        List<Object> list = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            byte[] content = new byte[1024 * 1024];
            list.add(content);
        }

        // 1秒钟遍历一下queue
        new Thread(()->{
            for (;;) {
                final Reference<? extends Date> poll = queue.poll();
                if (poll == dRef1) {
                    log.info("dRef1被回收了");
                }
                if (poll == dRef2) {
                    log.info("dRef2被回收了:{}", dRef2.get());
                }
                // 1秒检测1次
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        while (true) {
            if (counter.get() % 5 == 0) {
                log.info("每5秒触发一次GC");
                Runtime.getRuntime().gc();
            }
            if (counter.get() % 10 == 0) {
                log.info("每10秒触发一次GC");
                // 移除强引用
                 now = null;
                 log.info("now = {}", now);
            }
            counter.incrementAndGet();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
